<!DOCTYPE html>
<html>
<head>
    <title>GolfGeni服务器测试工具</title>
    <!--Import Google Icon Font-->
    <!--Import materialize.css-->
    <meta charset="UTF-8" />
    <link type="text/css" rel="stylesheet" href="/_test/assets/materialize.min.css"  media="screen,projection"/>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <style type="text/css">
        fieldset{
            border:1px solid #ccc;
        }
    </style>
</head>

<body class="green accent-4">

    <div class="container">
            <div class="row" style="margin-top:5px;">

                <div class="col s12 m6">
                    <form class="col s12 amber lighten-5 card">
                        <div class="row">
                            <div class="input-field col s12">
                                <input id="api_host" type="text" name="api_host">
                                <label for="api_host" data-error="wrong" data-success="right">调用接口域名，默认为本地</label>
                            </div>
                            <div class="input-field col s12">
                                <div class="input-field col m8">
                                    <input id="user_id" type="text" name="api_host">
                                    <label for="user_id" data-error="wrong" data-success="right">输入用户UID</label>
                                </div>

                                <div class="col m4">
                                    <a class="waves-effect waves-light btn-small grey" id="getIntegrals" style="margin-top:20px;">获取积分赛列表</a>
                                </div>
                            </div>
                            <div class="col s12">
                                <div class="input-field col m8">
                                    <select name="integrals" class="browser-default">
                                    </select>
                                </div>

                                <div class="col m4">
                                    <a class="waves-effect waves-light btn-large light-blue" id="playIntegral">进入积赛</a>
                                </div>
                            </div>
              <!--               <div class="col s12">
                                <div class="input-field col m8">
                                    <input id="room_id" type="text" name="room_id">
                                    <label for="room_id" data-error="wrong" data-success="right">房间ID</label>
                                </div>
                                <div class="col m4">
                                    <a class="waves-effect waves-light btn-large orange" id="joinRoom">加入房间</a>
                                </div>
                            </div> -->

                            <div class="col s12">
                                <div class="col m8">
                                    <a class="waves-effect waves-light btn-large red" id="disconnect">断开连接</a>
                                </div>
                                <div class="col m4">
                                    <a class="waves-effect waves-light btn-large green" id="playReady">发送开始</a>
                                </div>
                            </div>


                        </div>

                    </form>
                </div>


               <div class="col s12 m6">
                    <form class="col s12 amber lighten-5 card">
                            <div class="col s12" style="padding-top:10px;padding-bottom: 15px;">
                                <fieldset>
                                    <legend>回合结果</legend>
                     
                                    <div class="input-field col12">
                                        <input id="shot" type="text" name="shot">
                                        <label for="shot" data-error="wrong" data-success="right">回合杆数（包含罚杆）</label>
                                    </div>
                                    <div class="input-field col12">
                                        <input id="distance" type="text" name="distance">
                                        <label for="distance" data-error="wrong" data-success="right">距离（码）</label>
                                    </div>


                                    <a class="waves-effect waves-light btn-large" id="sendResult">发送回合结果</a>
                                </fieldset>

                                <fieldset>
                                    <legend>动作同步</legend>
                                    <div class="input-field col s12">
                                      <textarea id="play_action" name="play_action" class="materialize-textarea"></textarea>
                                      <label for="play_action">动作同步数据</label>
                                  </div>


                                    <a class="waves-effect waves-light btn-large purple" id="sendAction">发送同步数据</a>
                                </fieldset>
                            </div>

                    </form>
                </div>

            </div>

            <div class="row">
                <div class="col s12">
                    <div class="col s12 grey darken-4 card" style="color:#fff;font-size:12px;">
                        <p>> 调试信息 <span id="deviceStatInfo" style="color:#666;"></span></p>
                        <div id="console" style="max-height:400px;overflow-y:scroll;">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <iframe id="previewFrame" style="position:fixed;left:0;bottom:0;height:500px;display:none;" frameborder=0 src=""></iframe>


        <!--Import jQuery before materialize.js-->
        <script type="text/javascript" src="/_test/assets/md5.js"></script>
        <script type="text/javascript" src="/_test/assets/jquery.js"></script>
        <script type="text/javascript" src="/_test/assets/materialize.min.js"></script>
        <!-- <script src="https://sqimg.qq.com/expert_qq/webrtc/WebRTCAPI.min.js"></script> -->
        <script type="text/javascript">
          $(function(){
            var ws;
            var apiToken='';

            var logMsg=(msg,hasColor,url)=>{
                var d = new Date();
                var hour=d.getHours();
                var minute=d.getMinutes();
                var second=d.getSeconds();
                urlstr='';
                if(url){
                    urlstr='(<a target="_blank" href="'+url+'">'+url+'</a>)';
                }
                if(hasColor){
                    msg='<span style="color:#03a9f4;">'+msg+'</span>';
                }
                $('#console').prepend('<p class="logRow">'+hour+':'+minute+':'+second+'> '+msg+urlstr+'</p>')
            }

            var logError=(msg,url)=>{
                logMsg('<span style="color:red;">错误：'+msg+'</span>',url);
            }


            var initWs=(wsl,onOpen)=>{
                ws = new WebSocket(wsl);//新建立一个连接
                logMsg('初始化WebSocket',false,wsl);
                //如下指定事件处理 
                ws.onopen = function(){
                    logMsg('WebSocket连接成功');
                    onOpen()
                };  
                ws.onmessage = function(evt){
                    if(!evt.data)return;
                    logMsg("Websocket响应内容:"+evt.data);

                    var result=eval('('+evt.data+')')
                    console.log(result)

                    switch(result.type){
                        case 'integral_ready':
                        logMsg('等待匹配...',true);
                        break;
                        case 'game_start':
                        logMsg('匹配成功，等待点击发送开始...',true);
                        // sendData('request_play',[]);
                        break;
                        case 'user_out':
                        logError('用户退出游戏，UID：'+result.data.user_id)
                        break;
                        case 'play_ready':
                        logMsg('轮到用户'+result.data.play_user_id+'开始击球',true)
                        break;
                        case 'play_result':
                        logMsg('收到游戏结果数据',true)
                        break;
                        case 'play_action':
                        logMsg('收到游戏同步动作数据',true)
                        break;
                        case 'game_end':
                        logMsg('游戏结束',true);
                        break;
                        case 'error':
                        logError(result.msg);
                        break;
                    }
                };
                ws.onclose = function(evt){
                    logMsg('WebSocket连接断开');
                };  
                ws.onerror = function(evt){
                    logError('WebSocket错误');
                }; 
            }

            var sendData=(type,data)=>{
                var sentMsg=JSON.stringify({"type":type,"data":data});
                ws.send(sentMsg);
                logMsg('发送Websocket数据：'+sentMsg)
            }

            function getApiUrl(){
                return ''
            }

            function apiRequest(api,type,params,success,successMsg){
                var apiUrl=getApiUrl()+api
                logMsg('请求API('+type+'): '+apiUrl+' 参数: '+JSON.stringify(params))
                $.ajax({
                    url:apiUrl+(apiToken?'?api_token='+apiToken:''),
                    type:type,
                    data:params,
                    success:function(data){
                        logMsg('请求: '+apiUrl+' 成功')
                        success(data)
                    },
                    error:function(res){
                        // console.log(res)
                        logError('请求 '+apiUrl+' 失败，错误消息: "'+(res.responseJSON?res.responseJSON.message:'资源不存在')+'"')
                    }
                })
            }

            // 获取积分赛列表
            $('#getIntegrals').bind('click',function(){
                var uid=$('#user_id').val();
                apiRequest('/api/tests/user','get',{uid:uid},function(user){
                    apiToken=user.api_token;
                    apiRequest('/api/integrals','get',{uid:uid},function(integrals){
                        var integralHtml='';
                        for(var i in integrals){
                            var integral=integrals[i]
                            integralHtml+=('<option value="'+integral.id+'">'+integral.title+'</option>')
                        }
                        $('select[name="integrals"]').html(integralHtml)
                    })
                })
            })

            // 进入积分赛
            $('#playIntegral').bind('click',function(){
                apiRequest('/api/integrals/'+$('select[name="integrals"]').val(),'post',{
                    uid:$('#user_id').val()
                },function(data){
                    var wsUrl=data.ws_url

                    logMsg('开始连接Websocket...')
                    initWs(wsUrl,function(){
                        logMsg('连接Websocket成功')
                    })
                })
            })

            // 发送回合数据
            $('#sendResult').bind('click',function(){
                sendData('request_play_result',{
                    'distance':$('input[name="distance"]').val(),
                    'shot':$('input[name="shot"]').val()
                });
            })

            // 发送动作数据
            $('#sendAction').bind('click',function(){
                sendData('request_play_action',{
                    'data':$('textarea[name="play_action"]').val(),
                });
            })

            // 结束游戏
            $('#playReady').bind('click',function(){
                sendData('request_play',[]);
            })

            // 结束游戏
            $('#disconnect').bind('click',function(){
                ws.close()
            })
    })
</script>
</body>
</html>
